package com.liukaixin.product.ru.business.user.myapplies;

import android.os.Handler;
import android.support.annotation.NonNull;

import com.liukaixin.product.ru.business.user.myteams.MyTeamsContract;
import com.liukaixin.product.ru.data.CallBackListener;
import com.liukaixin.product.ru.data.model.Apply;
import com.liukaixin.product.ru.data.model.UserTeam;
import com.liukaixin.product.ru.data.repositories.TeamsRepository;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by liukaixin on 16/10/5.
 */

public class MyAppliesPresenter implements MyAppliesContract.Presenter {

    @NonNull
    private final TeamsRepository myTeamRepository;

    @NonNull
    private final MyAppliesContract.View MyAppliesView;

    private Handler handler = new Handler();

    public MyAppliesPresenter(@NonNull TeamsRepository teamsRepository,
                              @NonNull MyAppliesContract.View MyAppliesView) {
        this.myTeamRepository = checkNotNull(teamsRepository);
        this.MyAppliesView = checkNotNull(MyAppliesView);

        this.MyAppliesView.setPresenter(this);
    }

    @Override
    public void refresh() {
        MyAppliesView.initPage();
        // 获取第一页的十条数据
        getMyAppliesByUserId(1, 10);
    }

    @Override
    public void loadMore(Integer page) {
        getMyAppliesByUserId(page, 10);
    }

    private void getMyAppliesByUserId(Integer page, Integer rows) {
        myTeamRepository.getMyAppliesByUserId(page, rows,
                new CallBackListener<List<Apply>>() {
                    @Override
                    public void onCompleted() {
                        //do nothing
                    }

                    @Override
                    public void onError(String msg) {
                        MyAppliesView.showError(msg);
                    }

                    @Override
                    public void onNext(List<Apply> applies) {
                        showDataOnView(applies, page);
                    }
                });
    }

    private void showDataOnView(final List<Apply> applies,
                                final Integer page) {
        handler.postDelayed(() -> {
            if (page == 1 && applies.isEmpty()) {
                MyAppliesView.showNoData();
                return;
            }
            if (page == 1) {
                MyAppliesView.clearAdapter();
            }
            if (applies.size() % 10 > 0
                    || (page != 1 && applies.isEmpty())) {
                MyAppliesView.setNoMoreData();
            }
            MyAppliesView.showData(applies);
        }, 1000);
    }
}
